package com.bj58.groupbuy.action.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

	/**压缩文件
	 * @param zname  压缩包名
	 * @param source  源文件路径
	 */
	public static void createZip(String zname, String source) {
		try {
			ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zname));
			compressFile(zout, "", new File(source));
			zout.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**  
	 * @param zout   压缩输出流
	 * @param dir	文件夹名
	 * @param source 源文件路径
	 * @throws IOException
	 */
	private static void compressFile(ZipOutputStream zout, String dir,File source) throws IOException {
		if (source.isDirectory()) {
			File[] fs = source.listFiles();
			dir = dir + (dir.length() == 0 ? "" : "/") + source.getName();
			for (File f : fs) {
				compressFile(zout, dir, f);
			}
		} else {
			dir = dir.length() == 0 ? "" : dir + "/" + source.getName();
			ZipEntry entry = new ZipEntry(dir);
			zout.putNextEntry(entry);
			FileInputStream fin = new FileInputStream(source);
			int size = 0;
			byte[] buf = new byte[10240];
			while ((size = fin.read(buf, 0, 10240)) != -1) {
				zout.write(buf, 0, size);
			}
			fin.close();
		}
	}
	
	
	
	/**zip解压缩
	 * @param fin  文件输入流
	 * @param destdir	文件解压存放路径
	 * @return  解压后，压缩包下所有文件夹的完整路径
	 */
	public static List<String> unZip(InputStream fin, String destdir) {
		List<String>  fNameList = new ArrayList<String>();
		try {
			ZipInputStream zin = new ZipInputStream(fin);
			ZipEntry entry = null;
			String fName = ""; 
			while ((entry = zin.getNextEntry()) != null) {
				File filename = new File(destdir + entry.getName());
				File path = new File(filename.getParentFile().getPath()); // 确认目标目录存在、解压文件夹存在
				if (entry.isDirectory()) {
					fName = destdir + entry.getName();
					fNameList.add(fName);
					if (!filename.exists()) {
						filename.mkdirs();
					}
					zin.closeEntry();
					continue;
				}
				if (!path.exists()) {
					path.mkdirs();
				}
				FileOutputStream fout = new FileOutputStream(filename); // 得到目标文件流
				int size = 0;
				byte[] buf = new byte[256];
				while ((size = zin.read(buf)) != -1) { // 每个entry都有一个文件末尾的标识
					fout.write(buf, 0, size);
				}
				zin.closeEntry();
				fout.close();
			}
			fin.close();
			zin.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fNameList;
	}
	
}
